package com.picture.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.picture.context.BaseContext;
import com.picture.mapper.PictureMapper;
import com.picture.mapper.UserMapper;
import com.picture.mapper.UserPictureMapper;
import com.picture.pojo.dto.PictureStatusQueryDto;
import com.picture.pojo.dto.UserAssignDto;
import com.picture.pojo.entity.Picture;
import com.picture.pojo.entity.User;
import com.picture.pojo.entity.UserPicture;
import com.picture.pojo.vo.UserVo;
import com.picture.result.PageResult;
import com.picture.result.Result;
import com.picture.service.UserPictureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

import static com.picture.constant.Kindergarten.*;

@Service
public class UserPictureServiceImpl implements UserPictureService {
    @Autowired
    private PictureMapper pictureMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserPictureMapper userPictureMapper;

    /**
     * 查询未被标记的图片
     *
     * @param pictureStatusQueryDto
     * @return
     */
    @Override
    public Result<PageResult> listStatus(PictureStatusQueryDto pictureStatusQueryDto) {

       String description = pictureStatusQueryDto.getDescription();
       String aclass = pictureStatusQueryDto.getAclass();

        //1. 获取分页参数
        int page = pictureStatusQueryDto.getPage();
        int pageSize = pictureStatusQueryDto.getPageSize();
        if (page < 1 || pageSize < 1){
            //设置默认的分页参数
            page=1;
            pageSize=10;
        }
        Page<Picture> pages= new Page<>(page,pageSize);
        //2. 封装查询条件
        LambdaQueryWrapper<Picture> lqw=new LambdaQueryWrapper<>();
        //查询状态为未标记的图片
        lqw.eq(Picture::getPictureStatus,"0");
        //模糊查询学校和班级
        lqw.like(StringUtils.isNotBlank(description),Picture::getDescription,description)
                .or()
                .like(StringUtils.isNotBlank(aclass),Picture::getAclass,aclass);

        //3. 执行查询
        Page<Picture> picturePage1 = pictureMapper.selectPage(pages, lqw);

        //4. 封装返回结果
        long total = picturePage1.getTotal();
        List<Picture> records = picturePage1.getRecords();
        PageResult pageResult = new PageResult();
        pageResult.setTotal(total);
        pageResult.setRecords(records);
        return Result.success(pageResult);

    }

    /**
     * 查询有哪些用户
     * @return
     */
    @Override
    public Result<List<UserVo>> selectList() {
        List<User> list = new ArrayList<>();
        //1. 执行查询
        List<User> users = userMapper.selectList(null);
        List<UserVo> res=new ArrayList<>();
        //2. 封装返回结果
        for (User user : users) {
            String name = user.getName();
            if (AO_LIN_CHUN_TIAN.equals(name)|| FU_LIN_SHAN_ZHUANG.equals(name)|| FU_RONG_JING_CHENG.equals(name)||SAI_NA_YANG_GUANG.equals(name)
            ||SAN_HUN_LV_DAO.equals(name)||TAO_HUA_DAO.equals(name)||XIAN_DONG_TAO_LI.equals(name)){
                UserVo userVo = new UserVo();
                userVo.setId(user.getId());
                userVo.setName(user.getName());
                userVo.setWorkload(user.getWorkload());
                res.add(userVo);
            }
        }


        return Result.success(res);
    }

    /**
     * 分配图片给用户
     *
     * @param userAssignDto
     * @return
     */
    @Override
    @Transactional
    public Result assignPicture(UserAssignDto userAssignDto) {
        if ( userAssignDto.getUserId() == null){
            return Result.error("用户id不能为空");
        }
        List<Long> pictureIdList = userAssignDto.getPictureIdList();
        if (pictureIdList == null || pictureIdList.size() == 0){
            return Result.error("图片id不能为空");
        }

        //1. 执行分配
        for (Long aLong : pictureIdList) {
            UserPicture userPicture = new UserPicture();
            userPicture.setPictureId(aLong);
            userPicture.setUserId(userAssignDto.getUserId());
            userPictureMapper.insert(userPicture);
        }
        //2.用户工作量增加
        User user = userMapper.selectById(userAssignDto.getUserId());

        user.setWorkload(user.getWorkload()+pictureIdList.size());
        userMapper.updateById(user);
        //3. 图片状态修改
        for (Long aLong : pictureIdList) {
            Picture picture = pictureMapper.selectById(aLong);
            picture.setPictureStatus("3");
            pictureMapper.updateById(picture);
        }

        return Result.success("分配成功");
    }

    /**
     * 查询用户分配的图片
     *
     * @return
     */
    @Override
    @Transactional
    public Result<PageResult> selectPictureByUserId(PictureStatusQueryDto pictureStatusQueryDto) {
        Long userId = BaseContext.getCurrentId();
        if (userId == null){
            return Result.error("用户id不能为空");
        }
        //1. 获取分页参数
        int page = pictureStatusQueryDto.getPage();
        int pageSize = pictureStatusQueryDto.getPageSize();
        if (page < 1 || pageSize < 1){
            //设置默认的分页参数
            page=1;
            pageSize=10;
        }
        Page<Picture> pages= new Page<>(page,pageSize);
        //2. 执行查询
        List<UserPicture> userPictures = userPictureMapper.selectList(Wrappers.<UserPicture>lambdaQuery().eq(
                UserPicture::getUserId, userId
        ));
        if (userPictures == null || userPictures.size() == 0){
            return Result.success(null);
        }

        List<Long> pictureIdList = userPictures.stream().map(UserPicture::getPictureId).collect(Collectors.toList());

        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();

        queryWrapper.in("pictureId", pictureIdList);
        queryWrapper.eq("pictureStatus", 3);
        queryWrapper.like(StringUtils.isNotBlank(pictureStatusQueryDto.getDescription()),"description",pictureStatusQueryDto.getDescription())
                .like(StringUtils.isNotBlank(pictureStatusQueryDto.getAclass()),"class",pictureStatusQueryDto.getAclass());
        IPage<Picture> pictureIPage = pictureMapper.selectPage(pages, queryWrapper);
        long total = pictureIPage.getTotal();
        List<Picture> records = pictureIPage.getRecords();

        return Result.success(new PageResult(total,records));

    }


}
